package cn.xyz.mianshi.currency;

import cn.xyz.commons.utils.HttpClientUtil;
import cn.xyz.commons.utils.StringUtil;
import cn.xyz.mianshi.model.PageResult;
import cn.xyz.mianshi.utils.SKBeanUtils;
import cn.xyz.mianshi.vo.*;
import cn.xyz.repository.mongo.MongoRepository;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.bson.types.ObjectId;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.Query;
import org.mongodb.morphia.query.UpdateOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DigitalCurrencyManageImpl  extends MongoRepository<DigitalCurrency,ObjectId> {
    @Override
    public Datastore getDatastore() {
        return SKBeanUtils.getDatastore();
    }
    @Override
    public Class<DigitalCurrency> getEntityClass() {
        return DigitalCurrency.class;
    }
    private JSONArray getOTCRate()
    {
        Map params = new HashMap();//请求参数
        params.put("paramsData","USDT,ETH");
        String szResult  ="{\"_list\": [{\"coinName\": \"USDT\",\"sell\": \"--\"},{\"coinName\": \"ETH\",\"sell\": \"--\"}]}";
        try {
            //
            szResult =   HttpClientUtil.sendGetMessage(SKBeanUtils.getOtcConfig().getHuobigateway()+"/otc/getOtcInfo",params,"GET");
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject obj = JSONObject.parseObject(szResult);
        JSONArray _array =  obj.getJSONArray("_list");
        return _array;
    }
    public  Double getDigitalRate(String name)
    {
        if(name.equals("yestalk"))
        {
            return 1.0;
        }
        if(name.toUpperCase().indexOf("USDT")>-1)
        {
            name = "USDT";
        }
        JSONArray _rateArray = getOTCRate();
        String szResult = getDigitalRate(_rateArray,name);
        return  Double.parseDouble(szResult);
    }
    private String getDigitalRate(JSONArray _data,String name)
    {
        for(int i=0;i<_data.size();i++)
        {
          JSONObject _item =   _data.getJSONObject(i);
          String  coinName = _item.getString("coinName");
          if(coinName.equals(name))
          {
              return  _item.getString("sell");
          }
        }
        return "6.5";
    }

    /**
     * 获取数字货币列表
     * @return
     */
    public PageResult<DigitalCurrency> getDigitalList()
    {
        JSONArray _rateArray = getOTCRate();
        PageResult<DigitalCurrency> result = new PageResult<DigitalCurrency>();
        Query<DigitalCurrency> query = SKBeanUtils.getDatastore().createQuery(DigitalCurrency.class).order("-sort");
        List<DigitalCurrency> list= query.asList();
        for(int i=0;i<list.size();i++){
            list.get(i).setConvertRate(getDigitalRate(_rateArray,list.get(i).getName()));
        }
        result.setCount(query.count());
        result.setData(list);
        return  result;
    }
    public  void SaveDigitalList(String id,double minWithdrawalScore ,double withdrawaCharge,double minCheckWithdrawalSocre,Integer sort)
    {
        Query<DigitalCurrency> q = SKBeanUtils.getDatastore().createQuery(DigitalCurrency.class).field("_id").equal(new ObjectId(id));
        UpdateOperations<DigitalCurrency> ops=getDatastore().createUpdateOperations(DigitalCurrency.class);
        ops.set("withdrawaCharge",withdrawaCharge);
        ops.set("minWithdrawalScore",minWithdrawalScore);
        ops.set("minCheckWithdrawalSocre",minCheckWithdrawalSocre);
        ops.set("sort",sort);
        getDatastore().update(q, ops);
    }
    /**
     * 获取数字货币列表，以及余额
     * @param userID
     * @return
     */
    public List<DigitalCurrency> getDigitalCurrencyList(Integer userID)
    {
        JSONArray _rateArray = getOTCRate();

        Query<DigitalCurrency> query = SKBeanUtils.getDatastore().createQuery(DigitalCurrency.class).order("-sort");
        List<DigitalCurrency> list= query.asList();
        for(int i=0;i<list.size();i++){
            UserFollowCurrency q = SKBeanUtils.getDatastore().createQuery(UserFollowCurrency.class).field("userID").equal(userID).field("currencyID").equal(list.get(i).getId().toString()).get();
            if(q != null)
            {
                list.get(i).setFollow(true);
            }
            list.get(i).setBalance(SKBeanUtils.getDigitalSymbolManagelmpl().getUserMoeny(userID,list.get(i).getQueryName()));
            list.get(i).setBalance((double) Math.round(list.get(i).getBalance()* 1000000)/1000000);
            list.get(i).setConvertRate(getDigitalRate(_rateArray,list.get(i).getName()));
        }

        return list;
    }
    public List<DigitalCurrency> getDigitalCurrencyScoreList(Integer userID)
    {
        JSONArray _rateArray = getOTCRate();
        Query<DigitalCurrency> query = SKBeanUtils.getDatastore().createQuery(DigitalCurrency.class);
        List<DigitalCurrency> list= query.asList();
        for(int i=0;i<list.size();i++){
            //查询拥有的数字货币
            DigitalSymbol q = SKBeanUtils.getDatastore().createQuery(DigitalSymbol.class).field("userId").equal(userID).field("Symbol").equal(list.get(i).getQueryName()).get();

            if(q != null)
            {
                list.get(i).setBalance(q.getBalance());
            }
            else{
                list.get(i).setBalance(0.0);
            }

            list.get(i).setConvertRate(getDigitalRate(_rateArray,list.get(i).getName()));
            //list.get(i).setAccuracy(1000000);
        }
        return list;
    }

    public void addCurrencyInfo(String currencyName,String currencyIcon)
    {
        DigitalCurrency _data = new DigitalCurrency();
        _data.setFollow(false);
        _data.setCurrencyIcon(currencyIcon);
        _data.setCurrencyName(currencyName);
        SKBeanUtils.getDatastore().save(_data);
    }
    public void addCurrencyFollow(String currencyID,Integer userID)
    {
        UserFollowCurrency query = SKBeanUtils.getDatastore().createQuery(UserFollowCurrency.class).field("currencyID").equal(currencyID).field("userID").equal(userID).get();
        if(query == null)
        {
            UserFollowCurrency _item = new UserFollowCurrency();
            _item.setCurrencyID(currencyID);
            _item.setUserID(userID);
            SKBeanUtils.getDatastore().save(_item);
        }
    }
    public void delCurrencyFollow(String currencyID,Integer userID)
    {
        Query<UserFollowCurrency> query = SKBeanUtils.getDatastore().createQuery(UserFollowCurrency.class).field("currencyID").equal(currencyID).field("userID").equal(userID);
        if(query != null)
        {
            SKBeanUtils.getDatastore().delete(query);
        }
    }
    public List<DigitalCurrency> getFollowList(Integer userID)
    {
        JSONArray _rateArray = getOTCRate();
        Query<DigitalCurrency> query = SKBeanUtils.getDatastore().createQuery(DigitalCurrency.class);
        List<DigitalCurrency> list= query.asList();
        List<DigitalCurrency> newList= new  ArrayList<>();
        for(int i=0;i<list.size();i++){
            UserFollowCurrency q = SKBeanUtils.getDatastore().createQuery(UserFollowCurrency.class).field("userID").equal(userID).field("currencyID").equal(list.get(i).getId().toString()).get();
            if(q != null)
            {
                list.get(i).setFollow(true);
                list.get(i).setConvertRate(getDigitalRate(_rateArray,list.get(i).getName()));
                newList.add(list.get(i));
            }
        }
        return newList;
    }
    public String getShowName(String queryName)
    {
        DigitalCurrency query = SKBeanUtils.getDatastore().createQuery(DigitalCurrency.class).field("queryName").equal(queryName).get();
        if(query != null)
        {
            return query.getCurrencyName();
        }
        return queryName;
    }
}
